<template>
  <a-card :bordered="false">
    <!-- 查询区域 -->
    <div class="table-page-search-wrapper">
      <a-form layout="inline" @keyup.enter.native="searchQuery">
        <a-row :gutter="24">
          <a-col :xl="6" :lg="7" :md="8" :sm="24">
            <a-form-item label="名称">
              <a-input placeholder="请输入名称" v-model="queryParam.name"></a-input>
            </a-form-item>
          </a-col>
          <a-col :xl="6" :lg="7" :md="8" :sm="24">
            <a-form-item label="简介">
              <a-input placeholder="请输入简介" v-model="queryParam.synopsis"></a-input>
            </a-form-item>
          </a-col>
          <a-col :xl="6" :lg="7" :md="8" :sm="24">
            <a-form-item label="上架状态">
<!--              <a-input placeholder="请输入简介" v-model="queryParam.synopsis"></a-input>-->
<!--              <j-dict-select-tag type="list" v-model="queryParam.status" :trigger-change="true" dictCode="goods_status" placeholder="请选择状态"/>-->
              <a-select default-value="1"  @change="handleChange" ref="xuanze" :value="defaultValue">
                <a-select-option value="">
                  全部
                </a-select-option>
                <a-select-option value="-1">
                  已删除
                </a-select-option>
                <a-select-option value="1">
                  已上架
                </a-select-option>
                <a-select-option value="0">
                  已下架
                </a-select-option>
              </a-select>
            </a-form-item>
          </a-col>
          <a-col :xl="6" :lg="7" :md="8" :sm="24">
            <span style="float: left;overflow: hidden;" class="table-page-search-submitButtons">
              <a-button type="primary" @click="searchQuery" icon="search">查询</a-button>
              <a-button type="primary" @click="searchReset" icon="reload" style="margin-left: 8px">重置</a-button>
              <!--<a @click="handleToggleSearch" style="margin-left: 8px">
                {{ toggleSearchStatus ? '收起' : '展开' }}
                <a-icon :type="toggleSearchStatus ? 'up' : 'down'"/>
              </a>-->
            </span>
          </a-col>
        </a-row>
      </a-form>
    </div>
    <!-- 查询区域-END -->

    <!-- 操作按钮区域 -->
    <div class="table-operator">
      <a-button @click="handleAdd" type="primary" icon="plus">新增</a-button>
      <a-button @click="handleImport" type="primary" icon="import">导入ES</a-button>
      <a-button type="primary" icon="copy" @click="copyGoods()" :disabled="goodsCopyBtncomp" >复制商品</a-button>
      <a-button type="primary" icon="copy" @click="handleCoupon()" :disabled="couponAddBtn" >分配优惠券</a-button>
      <!--<a-button type="primary" icon="download" @click="handleExportXls('商品信息')">导出</a-button>
      <a-upload name="file" :showUploadList="false" :multiple="false" :headers="tokenHeader" :action="importExcelUrl" @change="handleImportExcel">
        <a-button type="primary" icon="import">导入</a-button>
      </a-upload>-->
      <a-dropdown v-if="selectedRowKeys.length > 0">
        <a-menu slot="overlay">
          <a-menu-item key="1" @click="batchDel"><a-icon type="delete"/>删除</a-menu-item>
        </a-menu>
        <a-button style="margin-left: 8px"> 批量操作 <a-icon type="down" /></a-button>
      </a-dropdown>
    </div>

    <!-- table区域-begin -->
    <div>
      <div class="ant-alert ant-alert-info" style="margin-bottom: 16px;">
        <i class="anticon anticon-info-circle ant-alert-icon"></i> 已选择 <a style="font-weight: 600">{{ selectedRowKeys.length }}</a>项
        <a style="margin-left: 24px" @click="onClearSelected">清空</a>
      </div>

      <a-table
        ref="table"
        size="middle"
        :scroll="{x:true}"
        bordered
        rowKey="id"
        :columns="columns"
        :dataSource="dataSource"
        :pagination="ipagination"
        :loading="loading"
        :rowSelection="{selectedRowKeys: selectedRowKeys, onChange: onSelectChange}"
        class="j-table-force-nowrap"
        @change="handleTableChange">

        <template slot="htmlSlot" slot-scope="text">
          <div v-html="text"></div>
        </template>
        <!--上下架状态-->
        <template slot="statusDictText" slot-scope="text,record">
          <div v-if="record.status=='0'" style="color: #eb2f96">{{text}}</div>
          <div v-else style="color: #00A0E9">{{text}}</div>
        </template>
        <template slot="imgSlot" slot-scope="text">
          <span v-if="!text" style="font-size: 12px;font-style: italic;">无图片</span>
          <img v-else :src="getImgView(text)" height="25px" alt="" style="max-width:80px;font-size: 12px;font-style: italic;"/>
        </template>
        <template slot="fileSlot" slot-scope="text">
          <span v-if="!text" style="font-size: 12px;font-style: italic;">无文件</span>
          <a-button
            v-else
            :ghost="true"
            type="primary"
            icon="download"
            size="small"
            @click="downloadFile(text)">
            下载
          </a-button>
        </template>

        <span slot="action" slot-scope="text, record">
          <a @click="handleEdit(record)">编辑</a>
          <a-divider type="vertical" />
          <a @click="handleStatus_dictText(record)">{{record.status=='1'?'下架':'上架' }}</a>
          <a-divider type="vertical" />
          <a-dropdown>
            <a class="ant-dropdown-link">更多 <a-icon type="down" /></a>
            <a-menu slot="overlay">
              <a-menu-item>
                <a @click="handleDetail(record)">详情</a>
              </a-menu-item>
              <a-menu-item>
                <a-popconfirm title="确定删除吗?" @confirm="() => handleDelete(record.id)">
                  <a>删除</a>
                </a-popconfirm>
              </a-menu-item>
            </a-menu>
          </a-dropdown>
        </span>

      </a-table>
    </div>

    <goods-modal ref="modalForm" @ok="modalFormOk"></goods-modal>
    <CouponListModal ref="couponModal" @ok="modalFormOk"></CouponListModal>
  </a-card>
</template>

<script>
  import { httpAction, getAction } from '@/api/manage'
  import JDictSelectTag from "@/components/dict/JDictSelectTag"
  import '@/assets/less/TableExpand.less'
  import { mixinDevice } from '@/utils/mixin'
  import { JeecgListMixin } from '@/mixins/JeecgListMixin1'
  import GoodsModal from './modules/GoodsModal'
  import {filterMultiDictText} from '@/components/dict/JDictSelectUtil'
  import { putAction } from '@/api/manage'
  import {initDictOptions, filterDictText} from '@/components/dict/JDictSelectUtil'
  import {filterDictTextByCache} from '@/components/dict/JDictSelectUtil'
  import pick from 'lodash.pick'
  import moment from 'moment'
  // import CouponList from '@/views/couponlist/CouponList'
  import CouponListModal from './modules/CouponListModal'
  export default {
    name: 'GoodsList',
    mixins:[JeecgListMixin, mixinDevice],
    components: {
      GoodsModal,
      CouponListModal,
      JDictSelectTag
    },
    data () {
      return {
        description: '商品信息管理页面',
        defaultValue:'1',
        /* table选中keys*/
        selectedRowKeys: [],
        /* table选中records*/
        selectionRows: [],
        //复制商品按钮显示
        goodsCopyBtn:true,
        // 表头
        columns: [
          {
            title: '序号',
            dataIndex: '',
            key:'rowIndex',
            width:60,
            align:"center",
            customRender:function (t,r,index) {
              return parseInt(index)+1;
            }
          },
          {
            title:'所属分类',
            align:"center",
            dataIndex: 'title',
            /*customRender: (t,r,index)=>{
              // return filterDictTextByCache('sex', t);
              return t
            }*/
          },
          {
            title:'名称',
            align:"center",
            dataIndex: 'name'
          },
          {
            title:'门店',
            align:"center",
            dataIndex: 'shopNames',
            /*customRender: (t,r,index)=>{
              let str = ''
              t.map((txt)=>{
                str+=txt.shop_name+','
              })
              return str.substring(0,str.lastIndexOf(','))
            }*/
          },
          {
            title:'简介',
            align:"center",
            dataIndex: 'synopsis',
            scopedSlots: {customRender: 'htmlSlot'}
          },
          {
            title:'商品图',
            align:"center",
            dataIndex: 'pic',
            scopedSlots: {customRender: 'imgSlot'}
          },
          {
            title:'团购图',
            align:"center",
            dataIndex: 'groupPurchasePic',
            scopedSlots: {customRender: 'imgSlot'}
          },
          {
            title:'轮播图',
            align:"center",
            dataIndex: 'albumPics',
            scopedSlots: {customRender: 'imgSlot'}
          },
          {
            title:'单位',
            align:"center",
            dataIndex: 'unit_dictText'
          },
          {
            title:'商品重量',
            align:"center",
            dataIndex: 'weight'
          },
          {
            title:'成本价',
            align:"center",
            dataIndex: 'costPrice'
          },
          {
            title:'建议售价',
            align:"center",
            dataIndex: 'suggestedPrice'
          },
          {
            title:'市场价',
            align:"center",
            dataIndex: 'originalPrice'
          },
          {
            title:'团购价格',
            align:"center",
            dataIndex: 'groupPurchasePrice'
          },
          {
            title:'关键字',
            align:"center",
            dataIndex: 'keywords'
          },
          {
            title:'成团人数',
            align:"center",
            dataIndex: 'groupSize'
          },
          {
            title:'限购数量',
            align:"center",
            dataIndex: 'limitedQuantity'
          },
          {
            title:'开始时间',
            align:"center",
            dataIndex: 'startTime'
          },
          {
            title:'结束时间',
            align:"center",
            dataIndex: 'endTime'
          },
          {
            title:'预计到货时间',
            align:"center",
            dataIndex: 'expectedArrivalDate'
          },
          {
            title:'上架状态',
            align:"center",
            dataIndex: 'status_dictText',
            scopedSlots: { customRender: 'statusDictText' }
          },
          /*{
            title:'删除状态[0:已删除,1:删除]',
            align:"center",
            dataIndex: 'deleted_dictText'
          },*/
          {
            title:'新品状态',
            align:"center",
            dataIndex: 'newStatus_dictText'
          },
          {
            title:'推荐状态',
            align:"center",
            dataIndex: 'recommandStatus_dictText'
          },
          {
            title:'排序',
            align:"center",
            dataIndex: 'sort'
          },
          /*{
            title:'商品详情',
            align:"center",
            dataIndex: 'detail'
          },*/
          /*{
            title:'创建人',
            align:"center",
            dataIndex: 'createBy'
          },
          {
            title:'创建时间',
            align:"center",
            dataIndex: 'createTime',
            customRender:function (text) {
              return !text?"":(text.length>10?text.substr(0,10):text)
            }
          },
          {
            title:'更新人',
            align:"center",
            dataIndex: 'updateBy'
          },
          {
            title:'更新时间',
            align:"center",
            dataIndex: 'updateTime',
            customRender:function (text) {
              return !text?"":(text.length>10?text.substr(0,10):text)
            }
          },*/
          {
            title: '操作',
            dataIndex: 'action',
            align:"center",
            fixed:"right",
            width:147,
            scopedSlots: { customRender: 'action' }
          }
        ],
        url: {
          list: "/goods/goods/list",
          delete: "/goods/goods/delete",
          deleteBatch: "/goods/goods/deleteBatch",
          exportXlsUrl: "/goods/goods/exportXls",
          importExcelUrl: "goods/goods/importExcel",
          audit:'/goods/goods/audit',
          add: "/goods/goods/add",
          edit: "/goods/goods/edit",
          queryById: "/goods/goods/queryById",
          import:"esGoods/importAll"
        },
        dictOptions:{},
      }
    },
    created() {
      this.queryParam.status = 1
      this.loadData()
      this.initDictConfig();
    },
    computed: {
      importExcelUrl: function(){
        return `${window._CONFIG['domianURL']}/${this.url.importExcelUrl}`;
      },
      goodsCopyBtncomp:function(){
        if(this.selectedRowKeys.length==1){
          return  false
        }else{
          return  true
        }
      },
      couponAddBtn:function() {
        if(this.selectedRowKeys.length>0){
          return  false
        }else{
          return  true
        }
      }
    },
    methods: {
      initDictConfig(){
      },
      //查询状态
      handleChange(e){
        console.log(e)
        // this.$refs.xuanze.value = e.toString()
        this.defaultValue = e
        this.queryParam.status = e
      },
      //查询重置
      searchReset() {
        this.defaultValue = ''
        this.queryParam = {}
        this.loadData(1);
      },
      //上下架操作
      handleStatus_dictText(record){
        let params = {id:record.id,status:record.status};
        putAction(this.url.audit,params).then((res)=>{
          console.log(res)
          if(res.success){
            this.$message.success(res.message)
            this.loadData(this.ipagination.current)
          }else {
            this.$message.error(res.message)
          }

        })
      },
      //复制商品
      onSelectChange(selectedRowKeys, selectionRows) {
        this.selectedRowKeys = selectedRowKeys;
        this.selectionRows = selectionRows;
        console.log('selectionRows',selectionRows)
        console.log('selectedRowKeys',selectedRowKeys)
      },
      copyGoods(){
        this.submitForm(this.selectionRows)
      },
      handleCoupon(){
        console.log(this.selectedRowKeys)
        //优惠券传参 ：商品或者门店的ID数组 + type类型（1：门店   2：商品）
        this.$refs.couponModal.add(this.selectedRowKeys,"2");
        this.$refs.couponModal.title = "分配优惠券";
        this.$refs.couponModal.disableSubmit = false;
      },
      modalFormOk() {
        // 新增/修改 成功时，重载列表
        this.loadData();
      },

      submitForm (record) {
        this.loading = true;
        const that = this;
        delete record[0]['id']
        record[0].createTime = moment(new Date().getTime()).format("YYYY-MM-DD HH:mm:ss")
        // record[0].createTime = new Date().getTime()
        // console.log(record[0])
        // 触发表单验证


        let httpurl = '';
        let method = '';

        httpurl+=this.url.add;
        method = 'post';

        let formData = record[0];
        console.log("表单提交数据",formData)
        httpAction(httpurl,formData,method).then((res)=>{
          if(res.success){
            that.$message.success(res.message);
            that.$emit('ok');
          }else{
            that.$message.warning(res.message);
          }
        }).finally(() => {
          this.selectedRowKeys = []
          this.selectionRows = []
          that.loading = false;
          this.loadData(this.ipagination.current)
        })



      },


      //导入
      handleImport(){
        getAction(this.url.import).then((res)=>{
          console.log(res)
          if (res.success){
            this.$message.success('成功导入'+res.result+'条')
          }
        })
      }
    }
  }
</script>
<style scoped>
  @import '~@assets/less/common.less';
</style>